package com.academy.teacher;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import com.academy.querystapp.R;
import com.academy.services.RequestMethod;
import com.academy.services.RestClient;
import com.academy.util.AcademyUtility;

public class ViewQuestionActivity extends Activity 
{
	Boolean value=true;
	RestClient restRequest;
	
	boolean flag = true;
	String message, title;
	ProgressDialog progress_Dialog;
	Boolean isProcessCompleted = false;
	
	private ArrayList<QuestionDetail> questionDetailsList;
	ListView lvViewQuestion;
	QuestionDetail questionDetail;
    public void onCreate(Bundle savedInstanceState) 
    {
    	 super.onCreate(savedInstanceState);
    	 setContentView(R.layout.view_question_listview);
    	 initializeViews();
    	 
    }
    
    @Override
    protected void onResume() 
    {
    	// TODO Auto-generated method stub
    	super.onResume();
    	questionDetailsList.clear();
    	getListofQuestions();
    }
    
    public void initializeViews()
    {
    	lvViewQuestion=(ListView) findViewById(R.id.listView1);
    	questionDetailsList=new ArrayList<QuestionDetail>();
    }
    
    public void getListofQuestions()
    {
    	value=true;	
		isProcessCompleted = false;
		progress_Dialog = ProgressDialog.show(ViewQuestionActivity.this, "","Loading..", true);
		AsyncTask<Void, Void, Boolean> waitForCompletion = new AsyncTask<Void, Void, Boolean>()
		{	
			protected Boolean doInBackground(Void... params)
			{
				while(isProcessCompleted == false)
				{	                      
					System.out.println("Login testdialog.......");
					try 
					{
						isProcessCompleted = true;
    					
    					restRequest = new RestClient(getString(R.string.viewStudentPostURL));
    					restRequest.AddParam(getString(R.string.TeacherID_param), AcademyUtility.getTeacherID());
    					restRequest.AddParam(getString(R.string.userType_Param),"ViewStudentPostedQuery");
//    					restRequest.AddParam(getString(R.string.type_paramname),"s");
    					try
    					{
    						restRequest.Execute(RequestMethod.GET);
    						System.out.println("Check the REsponse : "+restRequest.getResponse());
    					}
    					catch(Exception e)
    					{
    						System.out.println("Error in the execution"+e.toString());
    					}			      
//			    	  	parseResponse(restRequest.getResponse());
						
    					Thread.sleep(100);
					}
					catch (InterruptedException e)
					{
                  
					}
				}
				
				return true;
			};
		
			protected void onPostExecute(Boolean result) 
			{
				progress_Dialog.dismiss();
				if(result == true)
				{  
					 parseResponse(restRequest.getResponse());
    	  	  	}
				else
				{
       
				}
			}
		};
		waitForCompletion.execute(null, null, null);					
	}
    
    


private void parseResponse(String response)
{
	if(response==null ||response.equals("null"))
	{
		System.out.println("Response ---> "+response);
		isProcessCompleted= true;			
		showAlert(null, "No Server Found!");
	}
	else
	{
		try 
		{ 
		
			JSONObject RootObject = new JSONObject(response);
			System.out.println("JSON Object==> "+RootObject.toString());
			JSONObject studentPostObject = RootObject.getJSONObject("studentPost");
			JSONArray studentPostArray=studentPostObject.getJSONArray("studentPostData");
			String strStatus=studentPostObject.getString("status");
			System.out.println("studentPostArray="+studentPostArray);
			int length=studentPostArray.length();
			System.out.println("length count="+length);
			if(strStatus.equals("true"))
			{				
//				JSONObject studentPostDataObject;
				String strQuestion;
				for(int m=0;m<length;m++)
				{
					JSONObject studentPostDataObject=studentPostArray.getJSONObject(m);
					System.out.println("studentPostDataObject="+studentPostDataObject);
					strQuestion=studentPostDataObject.getString("question");
					System.out.println("strQuestion="+strQuestion);
					questionDetail=new QuestionDetail();
					questionDetail.setQuestion(strQuestion);
					questionDetailsList.add(questionDetail);
					System.out.println("questionDetailsList"+questionDetailsList);
				}
				System.out.println("questionDetailsList sancmn="+questionDetailsList);
				setAdapterForQuestionDetailList();
//				showAlert(null, "post in");
//				AcademyUtility.setName(studentData.getString("studentName"));
//				AcademyUtility.setCollegeName(studentData.getString("collageName"));
//				AcademyUtility.setCoarse(studentData.getString("course"));
//				AcademyUtility.setEmailID(studentData.getString("emailID"));
//				AcademyUtility.setStudentID(strUserName);
//				Intent ii=new Intent(this,QueryTabActivity.class);
//				startActivity(ii);
			}
			else if(strStatus.equals("false"))
			{
				String strError= studentPostObject.getString("errorDesc");
				showAlert(null, strError);
			}
		}
		catch (JSONException e) 
		{
			e.printStackTrace();
		} 
	}
}

	public void showAlert(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
//				Intent i=new Intent(StudentActivity.this,Homepage.class);
//				startActivity(i);
//				finish();
				
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}

	public void setAdapterForQuestionDetailList()
	{
		lvViewQuestion.setAdapter(new QuestionAdapter(getApplicationContext(), R.layout.question_list_item, questionDetailsList, this));
	}
    
}